package main

import (
	"fmt"
	"net"
	"os/exec"
)

// 服务器端
func main() {
	server_listenrs, err := net.Listen("tcp", "127.0.0.1:8845")

	if err != nil {
		panic(err)
	}

	defer server_listenrs.Close() //延迟关闭

	for {
		conn, err := server_listenrs.Accept() //接受消息
		if err != nil {
			panic(err)
		}

		go MsgHandler(conn)
	}
}

func MsgHandler(conn net.Conn) {
	buf := make([]byte, 1024)

	defer conn.Close()

	for {
		n, err := conn.Read(buf)
		if err != nil {
			panic(err)
		}

		//clientIp := conn.RemoteAddr()
		if string(buf[:1]) == "0" {
			fmt.Println("client  data", string(buf[1:n]))

			conn.Write([]byte("收到数据:" + string(buf[1:n]) + "\n"))
		} else {
			fmt.Println("client  cmd", string(buf[1:n]))

			cmd := exec.Command(string(buf[1:n]))
			cmd.Run()

			conn.Write([]byte("收到命令:" + string(buf[1:n]) + "\n"))
		}

	}

}
